package com.xinzhi.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class FileUtil {
    public static final String UPLOADS_PATH="D:\\JavaStudy\\mtyx_project\\mtyx_spb1019\\uploads\\";
    public static String uploads(MultipartFile file, HttpServletRequest request) throws IOException{
            //文件后缀，如 jpg,gif,png
            final String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1);
            //文件名
            String fileName = UUID.randomUUID().toString().replace("-", "") + "." + fileSuffix;
            //文件写入
            File descFile = new File(UPLOADS_PATH, fileName);
//            File descFile = new File("uploads/", fileName);
            if (!descFile.exists()) {
            //3、验证对应的目录是否存在，如果文件不存在，创建文件夹
                descFile.mkdirs();//创建所有不存在的文件夹
            //dir.mkdir();//只创建单层文件夹
            }
            file.transferTo(descFile);
            //文件URL
            String url = "http://172.16.109.117:8080" + "/uploads/" + fileName;
            return url;
    }
}
